package com.xu.system.controller;

import com.xu.base.enums.ResponseCodeEnum;
import com.xu.base.utils.AssertUtils;
import com.xu.security.model.OnlineUser;
import com.xu.security.utils.SecurityUtils;
import com.xu.system.auth.code.CodeAuthenticationToken;
import com.xu.system.model.pojo.login.CodeLoginReq;
import com.xu.system.model.pojo.login.PwdLoginReq;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录控制器
 *
 * @Author: 许乾伟
 * @Date: 2024/12/3 17:12
 */
@Slf4j
@RestController
public class LoginController {
    @Resource
    AuthenticationManager manager;
    /**
     * 密码用户登录
     * @param req
     * @return token
     */
    @PostMapping("pwdLogin")
    public OnlineUser pwdLogin(@RequestBody PwdLoginReq req){
        Authentication authenticate = manager.authenticate(new UsernamePasswordAuthenticationToken(req.getAccount(), req.getPwd()));
        AssertUtils.isNull(authenticate, ResponseCodeEnum.AUTH_FAILED, "登录失败");
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        OnlineUser onlineUser = (OnlineUser)authenticate.getPrincipal();
        return onlineUser;
    }

    /**
     * 工号登录
     * @param req
     * @return
     */
    @PostMapping("codeLogin")
    public OnlineUser codeLogin(@RequestBody CodeLoginReq req){
        Authentication authenticate = manager.authenticate(new CodeAuthenticationToken(req.getUserCode()));
        AssertUtils.isNull(authenticate, ResponseCodeEnum.AUTH_FAILED, "登录失败");
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        OnlineUser onlineUser = (OnlineUser)authenticate.getPrincipal();
        return onlineUser;
    }
    /**
     * 获取当前登录用户信息
     * @return
     */
    @GetMapping("getOnlineUser")
    public OnlineUser getOnlineUser(){
        return SecurityUtils.getLoginUser();
    }

}
